// index.js
// 获取应用实例
const app = getApp()
import {
  request
} from '../../request/index'
import regeneratorRuntime from '../../lib/runtime/runtime'
import PubSub from 'pubsub-js'


Page({
  data: {
    banners: [],
    recommend_list: [],
    recList: [],
    recommend_music: [],
    index:0

  },
  onLoad: function (optins) {
    this.getBanners(),
      this.getRecommendList(),
      this.getRecommendMusic()

          //订阅来自详情页的发布消息
    PubSub.subscribe('switchType',(msg,type)=>{
      let {recommend_music , index} = this.data
      if(type === 'pre'){ //上一首
        (index === 0) && (index = recommend_music.length)
        index -= 1
      }
      else if(type === 'loop'){ // 循环播放
        index = index
      }
      
      else{ //  下一首
        (index === recommend_music.length-1) && (index = -1)
        index += 1
      }

      this.setData({
        index
      })
      let musicId = recommend_music[index].id

      //发布消息
      PubSub.publish("musicId",musicId)

    })
  },
  //请求轮播图数据
  async getBanners() {
    let {
      data: {
        banners
      }
    } = await request({
      url: "/banner"
    })
    this.setData({
      banners
    })
  },

  //请求推荐歌单数据
  async getRecommendList() {
    let {
      data: {
        result
      }
    } = await request({
      url: "/personalized"
    })
    this.setData({
      recommend_list: result,
      recList: result.splice(0, 6)
    })
  },

  //请求推荐音乐数据
  async getRecommendMusic() {
    let {
      data: {
        result
      }
    } = await request({
      url: "/personalized/newsong"
    })
    this.setData({
      recommend_music: result.splice(0, 12),
    })
  },
  toDetail(e){
    let id = e.currentTarget.dataset.id
    let index = e.currentTarget.dataset.index

    this.setData({
      index
    })
    wx.navigateTo({
      url: '/pages/songDetail/index?id=' + id
    });
  },

})